<!--
 * @Date: 2020-03-17 17:39:47
 * @LastEditors: 黄栋
 * @LastEditTime: 2020-04-22 09:52:37
 * @FilePath: /cloudAdmin/src/views/market/promotion/shop/gift.vue
 --> 
<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/promotion' }">店铺营销</el-breadcrumb-item>
          <el-breadcrumb-item>赠品管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form inline size="small">
        <el-form-item>
          <el-select v-model="form.type" placeholder="赠品状态" style="width:150px">
            <el-option value>全部</el-option>
            <el-option value="1">进行中</el-option>
            <el-option value="2">已结束</el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button @click="addCoupon('')">新增赠品</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-button
        style="margin-bottom:10px"
        type="danger"
        size="small"
        @click="delCoupon('')"
        :disabled="dataListSelections.length <= 0"
      >批量删除</el-button>-->
      <el-table
        size="mini"
        :data="tableData"
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        :header-cell-style="{background:'#F7F7F7',color:'#1E1E1E'}"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="优惠券名称"></el-table-column>
        <el-table-column width="260px" label="有效期" show-overflow-tooltip>
          <template slot-scope="{row}">{{row.start_time}} - {{row.end_time}}</template>
        </el-table-column>
        <el-table-column prop="number" label="库存"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row}">
            <span v-if="row.status==1">已开启</span>
            <span v-else>已禁用</span>
          </template>
        </el-table-column>
        <el-table-column width="190px" label="操作">
          <template slot-scope="{row}">
            <el-button @click="addCoupon(row.id)" type="text">详情</el-button>
            <el-button @click="addCoupon(row.id)" v-if="row.status==1" type="text">修改</el-button>
            <el-button @click="delCoupon(row.id)" type="text">删除</el-button>
            <el-button @click="changeStatus(row)" type="text">
              <span v-if="row.status==1">禁用</span>
              <span v-else>开启</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.page_num"
        :total="form.total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-card>
    <el-dialog title="赠品详情" width="550px" :close-on-click-modal="false" :visible.sync="visible">
      <el-form ref="dataForm" size="small" :rules="dataRule" :model="editForm" label-width="90px">
        <el-form-item label="赠品名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="赠品图片">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :data="uploadData"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="editForm.image_url" :src="editForm.image_url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="赠品库存">
          <el-input v-model="editForm.number"></el-input>
        </el-form-item>
        <el-form-item label="赠送类型">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="1">满多少元赠送</el-radio>
            <el-radio :label="2">满多少件赠送</el-radio>
          </el-radio-group>
          <div>
            <el-input v-if="editForm.type==1" v-model="editForm.min_price"></el-input>
            <el-input v-if="editForm.type==2" v-model="editForm.min_munber"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="适用产品">
          <el-radio-group v-model="editForm.is_all">
            <el-radio :label="1">全部商品</el-radio>
            <el-radio :label="2">部分商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否开启">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="2">暂不开启</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="editForm.is_all==2" label="选择产品">
          <div class="goodsBox">
            <div class="goodsItems" :key="index" v-for="(item,index) in goodList">
              <div class="img">
                <img :src="item.thumb" alt />
                <i class="el-icon-delete" @click="goodList.splice(idnex,1)"></i>
              </div>
              <p>{{item.title}}</p>
            </div>
          </div>
        </el-form-item>
        <el-button
          size="mini"
          v-if="editForm.is_all==2"
          type="primary"
          @click="innerVisible=true"
        >添加商品</el-button>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取消</el-button>
        <el-button size="small" type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>

      <el-dialog width="800px" title="选择产品" :visible.sync="innerVisible" append-to-body>
        <el-form inline size="small" label-width="90px">
          <el-form-item label="产品名称">
            <el-input v-model="search.keywords"></el-input>
          </el-form-item>
          <el-form-item label="实际销量">
            <el-col :span="11">
              <el-input v-model="search.sell_1"></el-input>
            </el-col>
            <el-col :span="2" style="text-align:center">-</el-col>
            <el-col :span="11">
              <el-input v-model="search.sell_2"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="一级分类">
            <!-- <el-input v-model=""></el-input> -->
            <el-select style="width:178px" v-model="search.categoryid" placeholder="请选择">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一口价">
            <el-col :span="11">
              <el-input v-model="search.price_1"></el-input>
            </el-col>

            <el-col :span="2" style="text-align:center">-</el-col>
            <el-col :span="11">
              <el-input v-model="search.price_2"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
        <el-card>
          <div class="goodsBox">
            <div
              class="goodsItem"
              :key="index"
              v-for="(item,index) in productList"
              @click="selectItem(item)"
              :class="{checked:selectId.includes(item.id)}"
            >
              <div class="img">
                <img :src="item.thumb" alt />
              </div>
              <p>{{item.title}}</p>
            </div>
          </div>
          <el-pagination
            style="padding:10px;"
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :current-page="search.page"
            :page-size="search.page_num"
            :total="search.total"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  get_gift_list,
  get_gift_info,
  get_category_list,
  add_gift,
  del_gift,
  edit_gift_status,
  get_goods_list
} from "@/utils/api/market";
import httpRequest from "@/utils/httpRequest";
import { mapState, mapActions } from "vuex";

export default {
  computed: {
    ...mapState({
      company: state => state.company
    }),
    selectId() {
      if (this.goodList && this.goodList.length > 0) {
        let arrIds = this.goodList.map(item => item.id);
        return arrIds;
      } else {
        return [];
      }
    }
  },
  watch: {
    selectId(nval, oval) {
      this.editForm.goods_id = nval.join(",");
    }
  },
  data() {
    return {
      action: httpRequest.adornUrl("/market/upload/upload"),
      uploadData: { type: "2" },
      form: {
        page_num: 10,
        page: 1,
        total: 0
      },
      search: {
        page_num: 10,
        page: 1,
        total: 0,
        keywords: "",
        categoryid: "",
        sell_1: "",
        sell_2: "",
        price_1: "",
        price_2: ""
      },
      categoryList: [],
      productList: [],
      goodList: [],
      dataListLoading: false,
      innerVisible: false,
      dataListSelections: [],
      editForm: {},
      tableData: [],
      visible: false,
      dataRule: {
        name: [
          { required: true, message: "快递单号不能为空", trigger: "blur" }
        ],
        reduce: [
          { required: true, message: "满减金额不能为空", trigger: "blur" }
        ],
        min_price: [
          { required: true, message: "使用最小金额不能为空", trigger: "blur" }
        ],
        member_num: [
          { required: true, message: "每人可领取数量不能为空", trigger: "blur" }
        ],
        number: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        start_time: [
          { required: true, message: "有效期开始时间不能为空", trigger: "blur" }
        ],
        end_time: [
          { required: true, message: "有效期截止时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  activated() {
    this.getDataList();
    get_category_list({ to_co_id: this.company.id, parentid: 0 }).then(res => {
      if (res.code == 200) {
        this.categoryList = res.data;
      }
    });
  },

  methods: {
    getDataList() {
      get_gift_list(this.form).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.form.total = res.data.total;
        }
      });
    },
    /**显示 */
    addCoupon(id) {
      this.editForm = {
        name: "",
        goods_id: "",
        end_time: "",
        min_price: 0,
        type: 1,
        min_munber: 0,
        is_all: "",
        start_time: "",
        image_url: "",
        number: ""
      };
      this.goodList = [];
      if (id) {
        get_gift_info({ id: id }).then(res => {
          if (res.code == 200) {
            this.editForm = {
              id: res.data.id,
              co_id: res.data.co_id || "",
              name: res.data.name,
              image_url: res.data.image_url,
              goods_id: res.data.goods_id,
              number: res.data.number,
              min_munber: res.data.min_munber || 0,
              min_price: res.data.min_price || 0,
              status: res.data.status,
              is_all: res.data.is_all,
              type: res.data.type
            };
            if (res.data.list) {
              this.goodList = res.data.list;
            }
          }
        });
      }
      this.visible = true;
    },
    /**主图上传回调 */
    handleSuccess(res, file) {
      this.editForm.image_url = res.data.file_url;
    },
    /**添加/修改 优惠券 */
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          add_gift(this.editForm).then(res => {
            this.visible = false;
            if (res.code == 200) {
              this.$message({
                message: res.message,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },

    /**启用禁用 */
    changeStatus(data) {
      edit_gift_status({ id: data.id, status: data.status == 1 ? 2 : 1 }).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(res.message);
          }
        }
      );
    },
    /**获取商品列表 */
    getList() {
      get_goods_list(this.search).then(res => {
        this.productList = res.data.list;
      });
    },
    /** */
    selectItem(item) {
      if (this.selectId.includes(item.id)) {
        //includes()方法判断是否包含某一元素,返回true或false表示是否包含元素，对NaN一样有效
        //filter()方法用于把Array的某些元素过滤掉，filter()把传入的函数依次作用于每个元素，然后根据返回值是true还是false决定保留还是丢弃该元素：生成新的数组
        this.goodList = this.goodList.filter(function(ele) {
          return ele.id != item.id;
        });
        //this.arr=this.arr.filter((ele)=>ele!=i);
        //filter()为假时删除
      } else {
        this.goodList.push(item);
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    /**删除优惠券 */
    delCoupon(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        del_gift({ id: ids.join(",") }).then(res => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    /**批量 */
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 每页数
    handleSizeChange(val) {
      this.form.page_num = val;
      this.form.page = 1;
      this.getDataList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.form.page = val;
      this.getDataList();
    },
    // 每页数
    handleSizeChange2(val) {
      this.search.page_num = val;
      this.search.page = 1;
      this.getList();
    },
    // 当前页
    handleCurrentChange2(val) {
      this.search.page = val;
      this.getList();
    }
  }
};
</script>

<style lang="less">
.line {
  text-align: center;
  vertical-align: bottom;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
  display: block;
}
.goodsBox {
  display: flex;
  flex-wrap: wrap;
}
.goodsPosition {
  width: 120px;
}
.goodsItems {
  display: flex;
  flex-direction: column;
  width: 80px;
  height: 80px;
  justify-content: center;
  align-items: center;
  // background-color: #fff;
  p {
    line-height: 1;
    margin: 0;
    text-align: center;
    font-size: 12px;
    margin-top: 5px;
  }
  .img {
    width: 40px;
    height: 40px;
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    i {
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
      color: #eb3941;
    }
  }
}
.goodsItem {
  display: flex;
  padding: 10px;
  width: 133px;
  border: 1px solid #e6e6e6;
  border-radius: 5px;
  align-items: center;
  font-size: 12px;
  margin: 5px;
  cursor: pointer;
  &.checked {
    border: 2px solid #096dd9;
  }
  .img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>